<template>
  <div class="message-container"  ref="mainContainer" v-loading="isLoading">
    <MessageArea
      v-if="data.total"
      title="评论列表"
      :total="data.total"
      :list="data.rows"
      :isListLoading="isLoading"
      @submit="handleSubmit"
    />
    <div class="message-end" v-if="!isMore&&data.total">已经到底部啦~~</div>
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import {postMessage,getMessage} from "@/api/message.js"
import fetchData from "@/mixins/fetchData.js";
import {debounce} from "@/utils"
export default {
  mixins: [fetchData({total:0,rows:[]})],
  data(){
    return {
      page:1,
      limit:10
    }
  },
  computed:{
    isMore(){
      return this.data.total > this.data.rows.length;
    }
  },
  components:{
    MessageArea
  },
  methods:{
    async fetchData(){
      return await getMessage(this.page,this.limit);
    },
    async moreFectData(){
      if(!this.isMore) return;
      this.isLoading = true;
      const resp =  await this.fetchData();
      this.page++;
      this.data.total = resp.total;
      this.data.rows.push(...resp.rows)
      console.log(resp)
      this.isLoading = false;
    },
    async handleSubmit(body,callback){
     const {content , name} = body;
      const result =  await postMessage({content,nickname:name});
      this.data.total++;
      this.data.rows.unshift(result);
      callback('评论成功');
    },
    handleScroll(){
      const range = 100; //小于这个范围就算到底部
      const flagg = this.$refs.mainContainer.scrollHeight - range<=this.$refs.mainContainer.clientHeight+this.$refs.mainContainer.scrollTop
      if(this.isLoading || !flagg) return;
      
      this.moreFectData()
    }
  },
  mounted() {
    //监听滚动条变化
    const handleScrollDebounce = debounce(this.handleScroll);     //防抖函数，避免函数的多次执行
    this.$refs.mainContainer.addEventListener("scroll", handleScrollDebounce);
  },
  beforeDestroy() {
    this.$refs.mainContainer.removeEventListener("scroll", this.handleScroll);
  },
}
</script>

<style scoped lang='less'>
@import "~@/styles/mixin.less";
@import "~@/styles/var.less";
.message-container{
  width: 650px;
  height: 100%;
  margin: 0 auto;
  .self-scroll();
  &::-webkit-scrollbar {
    display: none;
  }
}
.message-end{
  height: 30px;
  text-align: center;
  font-size: 15px;
  color: @gray;
}
</style>